package net.stock.controller;

import com.google.appengine.api.users.UserService;
import net.stock.db.UserAccess;
import net.stock.service.RequestDao;
import net.stock.utils.StockUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author naim
 */
public class LoginFilter implements Filter {
    private UserService userService;
    private RequestDao requestDao;

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain)
            throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        if (userService.isUserLoggedIn()) {
            if (!userService.isUserAdmin()) {
                UserAccess ua = requestDao.getUserAccess(userService.getCurrentUser().getEmail());
                if (ua == null) {
                    response.sendRedirect(StockUtils.ERROR_PAGE + "?type=" + StockUtils.ERROR_TYPE_NOT_YET_REQUESTED);
                    return;
                } else if (!ua.isHasAccess()) {
                    response.sendRedirect(StockUtils.ERROR_PAGE + "?type=" + StockUtils.ERROR_TYPE_REQUEST_NOT_YET_ACCEPTED);
                    return;
                }
            }
            filterChain.doFilter(req, res);
        } else {
            response.sendRedirect(userService.createLoginURL(request.getRequestURI()));
        }
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    public void setRequestDao(RequestDao requestDao) {
        this.requestDao = requestDao;
    }

    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void destroy() {
    }
}
